package cn.zhangtiancinb.simple_demo.http.controller;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.zhangtiancinb.simple_demo.http.utils.ExceptionSwitchConfigProperties;
import cn.zhangtiancinb.simple_demo.exception_switch.client.ExceptionSwitchUtil;

/**
 * HTTP 请求
 *
 * @author 张天赐
 */
@RestController
@RequestMapping("/http")
public class HttpController {

    @Value("${number:3}")
    Integer number;
    @Resource
    ExceptionSwitchConfigProperties exceptionSwitchConfig;

    /**
     * 默认实现
     *
     * @param value 用于判断是否出错的参数
     * @return 函数结果
     */
    @ResponseBody
    @RequestMapping(value = "default")
    public String auto(@RequestParam(required = false, defaultValue = "0") Integer value) {
        ExceptionSwitchUtil.getInstance(BeanUtil.beanToMap(exceptionSwitchConfig)).callQuickly("应用[simple_demo.http]服务[http]方法[default]");
        // 返回200
        if (value % number != 0) {return HttpStatus.OK.toString(); }
        // 触发自定义异常
        else { throw new RuntimeException("Happen an error!"); }
    }

    /**
     * 状态码总是200
     *
     * @param value 用于判断是否出错的参数
     * @return 函数结果
     */
    @ResponseBody
    @RequestMapping(value = "always200")
    public String alwaysOk(@RequestParam(required = false, defaultValue = "0") Integer value) {
        ExceptionSwitchUtil.getInstance(BeanUtil.beanToMap(exceptionSwitchConfig)).callQuickly("应用[simple_demo.http]服务[http]方法[always200]");
        // 返回200
        if (value % number != 0) {return HttpStatus.OK.toString(); }
        // 触发自定义异常
        else {return HttpStatus.INTERNAL_SERVER_ERROR.toString(); }
    }
}
